package ar.edu.utn.frre.sistop.simumem.fragments;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import ar.edu.utn.frre.sistop.simumem.DataLoadActivity;
import ar.edu.utn.frre.sistop.simumem.R;
import ar.edu.utn.frre.sistop.simumem.common.Preferences;
import ar.edu.utn.frre.sistop.simumem.model.Particion;

public class PartitionLoadFragment extends Fragment {

	private PartitionAdapter mAdapter;
	private ArrayList<Particion> mData;
	private LinearLayout mHeader;
	private ListView mParticionesListView;
	private EditText mTamano;
	private ImageView mAgregarParticion;
	private Preferences mPreferences;

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getActivity().setTitle(R.string.titleDataLoad_Particiones);
		mPreferences = ((DataLoadActivity) getActivity()).getPreferences();

		if (mData == null) {
			mData = new ArrayList<Particion>();
		}

		if (mAdapter == null) {
			mAdapter = new PartitionAdapter(getActivity(), mData);
		}

		// setListAdapter(mAdapter);
		obtenerHandlesDeVistas();
		mParticionesListView.setAdapter(mAdapter);
		mParticionesListView.setEmptyView(getActivity().findViewById(R.id.empty_list_partitions));
		if (mAdapter.getCount() == 0) {
			mHeader.setVisibility(View.GONE);
		} else {
			mHeader.setVisibility(View.VISIBLE);
		}

		// agregar particion
		mTamano.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == R.id.action_add_partition || actionId == EditorInfo.IME_ACTION_DONE) {
					agregarParticion();
					return true;
				}
				return false;
			}
		});

		mAgregarParticion.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				agregarParticion();
			}
		});

		// remover particion
		mParticionesListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == (mData.size() - 1)) {
					mData.remove(position);
					mAdapter.notifyDataSetChanged();
					checkHeaderVisibility();
					return true;
				} else {
					Toast.makeText(getActivity(), R.string.toastPartitionHolesWarning,
							Toast.LENGTH_LONG).show();
				}
				return false;
			}
		});
	}
	
	@Override
	public void onResume() {
		recuperarParticiones();
		checkHeaderVisibility();
		super.onResume();
	}
	
	@Override
	public void onPause() {
		guardarParticiones();
		super.onPause();
	}
	
	public void recuperarParticiones() {
		mData.clear();
		for (Particion particion : mPreferences.getParticiones()) {
			mData.add(particion);
		}
		mAdapter.notifyDataSetChanged();
	}
	
	public void guardarParticiones() {
		mPreferences.setParticiones(mData);
	}
	
	public void checkHeaderVisibility() {
		if (mAdapter.getCount() == 0) {
			mHeader.setVisibility(View.GONE);
		} else {
			mHeader.setVisibility(View.VISIBLE);
		}
	}

	protected void agregarParticion() {
		if (TextUtils.isEmpty(mTamano.getText())) {
			Toast.makeText(getActivity(), R.string.toastIncompleteField_Partition,
					Toast.LENGTH_SHORT).show();
		} else if (Long.parseLong(mTamano.getText().toString()) == 0) {
			Toast.makeText(getActivity(), R.string.toastZeroPartitionSize, Toast.LENGTH_SHORT)
					.show();
		} else {
			Particion particion = new Particion();
			particion.setId(mData.size());
			if (mData.size() == 0) {
				particion.setInicio(0);
			} else {
				particion.setInicio(mData.get(mData.size() - 1).getInicio()
						+ mData.get(mData.size() - 1).getTamano());
			}
			particion.setTamano(Long.parseLong(mTamano.getText().toString()));
			mTamano.setText("");
			mData.add(particion);
			mAdapter.notifyDataSetChanged();
			if (mAdapter.getCount() == 1) {
				mHeader.setVisibility(View.VISIBLE);
			}
			mParticionesListView.post(new Runnable() {

				@Override
				public void run() {
					mParticionesListView.setSelection(mAdapter.getCount() - 1);
					mTamano.requestFocus();
				}
			});
		}
	}

	private void obtenerHandlesDeVistas() {
		mHeader = (LinearLayout) getActivity().findViewById(R.id.llDataLoadPartition_header);
		mParticionesListView = (ListView) getActivity().findViewById(R.id.list_partitions);
		mTamano = (EditText) getActivity().findViewById(R.id.txtDataLoadPartition_size);
		mAgregarParticion = (ImageView) getActivity().findViewById(
				R.id.imgDataLoadPartition_addPartition);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rooView = inflater.inflate(R.layout.fragment_data_load_partition, container, false);
		return rooView;
	}

	public ArrayList<Particion> getParticiones() {
		return mData;
	}
}